package timing_task

import (
	"fmt"
	"strconv"
	"strings"
	"time"
	"wx_build/core/build"
	"wx_build/core/logs"
	"wx_build/global"
	"wx_build/model/tables"
)

// Run 开始运行这个任务
func Run() {
	for {
		start()
		time.Sleep(1 * time.Second)
	}
}

// 开始执行
func start() {
	db := global.Sqlite
	list := new([]tables.Task)
	db.Where("status = ?", "待运行").Find(&list)
	for _, v := range *list {
		project := getProject(v.ProjectId)
		project.LatestVersion = getVersion(project.LatestVersion)
		err := build.Run(project, v.TaskId)
		if err != nil {
			logs.Err("构建失败" + err.Error())
		}
		updateTask(v.TaskId, project)

	}
}
func getVersion(version string) string {
	if version == "" {
		return "1.0.0"
	}
	versionList := strings.Split(version, ".")
	First, _ := strconv.Atoi(versionList[0])
	Second, _ := strconv.Atoi(versionList[1])
	Third, _ := strconv.Atoi(versionList[2])
	if Third == 99 {
		if Second == 99 {
			First += 1
		} else {
			Second += 1
		}
	} else {
		Third += 1
	}
	return fmt.Sprintf("%d.%d.%d", First, Second, Third)

}

// 更新任务状态
func updateTask(taskId string, project tables.Project) {
	task := tables.Task{
		TaskId: taskId,
	}
	err := task.QueryOne(&task)
	if err != nil {
		logInfo := fmt.Sprintf("查询任务失败，任务id：%s", taskId)
		logs.Err(logInfo, err)
		fmt.Println(logInfo, err.Error())
	}
	task.Status = "已完成"
	task.Version = project.LatestVersion
	db := global.Sqlite
	err = db.Save(&task).Error
	if err != nil {
		logInfo := fmt.Sprintf("更新任务失败，任务id：%s", taskId)
		logs.Err(logInfo, err)
		fmt.Println(logInfo, err.Error())
	}
	db.Save(&project)
	if err != nil {
		logInfo := fmt.Sprintf("更新项目版本失败，任务id：%s", taskId)
		logs.Err(logInfo, err)
		fmt.Println(logInfo, err.Error())
	}
}

// 获取单个项目
func getProject(projectId string) tables.Project {
	project := tables.Project{
		ProjectId: projectId,
	}
	err := project.QueryOne(&project)
	if err != nil {
		logInfo := fmt.Sprintf("查询项目失败，项目id：%s", projectId)
		logs.Err(logInfo, err)
		fmt.Println(logInfo, err.Error())
	}
	return project
}
